package ru.len.cafe.ejb.security;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import ru.len.cafe.entity.model.Employe;

public class HashGenerator {

    /**
     * Generates SHA-256 hash
     * @param toHash
     * @return 
     * @throws NoSuchAlgorithmException
     */
    public static String generateHash(String toHash) 
    				throws NoSuchAlgorithmException{
    	
    	String message = toHash;
	 
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(message.getBytes());
 
        byte byteData[] = md.digest();
 
        StringBuffer hexString = new StringBuffer();
    	for (int i=0;i<byteData.length;i++) {
    		String hex=Integer.toHexString(0xff & byteData[i]);
   	     	if(hex.length()==1) hexString.append('0');
   	     	hexString.append(hex);
    	}
    	
    	return hexString.toString();
    }
    
    /**
     * Same thing @link generateHash(String toHash), but Employe passed into the method 
     * @param employe
     * @return
     */
    public static String generateHash(Employe employe){
	try {
	    String temp = generateHash( employe.getLogin() + 
		    employe.getPassword() + 
		    System.currentTimeMillis() + 
		    "somerubbish77070" );
	    
	  //hashing hash second time for more security =) 
	    return generateHash(temp);
	} catch (NoSuchAlgorithmException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return null;
    }
    
    /**
     * Generates hash for user password
     * @param password
     * @return md5 hash
     */
    public static String hashPassword(String password){
	String hashword = null;
	try {
	    MessageDigest md5 = MessageDigest.getInstance("MD5");
	    md5.update(password.getBytes());
	    BigInteger hash = new BigInteger(1, md5.digest());
	    hashword = hash.toString(16);
	} catch (NoSuchAlgorithmException nsae) {
	    // ignore
	}
	return hashword;    
    }
    
}
